package com.web.controller;

import com.core.logMonitor.Log4jAsyncWriter;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/10/12
 * Time: 16:07
 * To change this template use Editor | File and Code Templates.
 */
@Controller
@RequestMapping("/log4jmonitor")
public class LogMonotorController {

    private static Logger log = Logger.getLogger(LogMonotorController.class);

    @RequestMapping("/index")
    public void logMonotor(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Cache-Control", "private");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println("<!-- author by lxf -->\n");
        writer.flush();

        final AsyncContext ac = request.startAsync();
        ac.setTimeout(1 * 60 * 60 * 1000);//1小时
        ac.addListener(new AsyncListener() {
            public void onComplete(AsyncEvent event) throws IOException {
                ac.getResponse().getWriter().close();
                Log4jAsyncWriter.deleteAc(ac);
                log.info("AsyncListener onComplete");
            }

            public void onTimeout(AsyncEvent event) throws IOException {
                ac.getResponse().getWriter().close();
                Log4jAsyncWriter.deleteAc(ac);
                log.info("AsyncListener onTimeout");
            }

            public void onError(AsyncEvent event) throws IOException {
                ac.getResponse().getWriter().close();
                Log4jAsyncWriter.deleteAc(ac);
                log.info("AsyncListener onError");
            }

            public void onStartAsync(AsyncEvent event) throws IOException {
                log.info("AsyncListener onStartAsync");
            }
        });
        Log4jAsyncWriter.addAc(ac);
    }

    @RequestMapping(value = "test")
    public void testlog() {
        log.debug("this is debug log!");
    }

}
